package com.zhihao.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhihao.takeaway.common.utils.EasyUITable;
import com.zhihao.takeaway.common.utils.JwtUtil;
import com.zhihao.takeaway.entity.Category;
import com.zhihao.takeaway.mapper.CategoryMapper;
import com.zhihao.takeaway.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public String getCategoryId(String name){

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getName,name);
        Category category = categoryMapper.selectOne(queryWrapper);
        if(category != null){
            return category.getId();
        }else{
            return null;
        }
    }

    @Override
    public EasyUITable getTableData(Integer currentPage) {
        IPage page = new Page(currentPage,6);
        categoryMapper.selectPage(page,null);
        List<Category> list = page.getRecords();
        Integer total = (int)page.getTotal();
        return new EasyUITable(total,list);
    }

    @Override
    public Integer deleteById(String id) {
        Integer num  = categoryMapper.deleteById(id);
        return num;
    }

    @Override
    public Integer updateCategory(Category category) {
        Integer num =  categoryMapper.updateById(category);
        return num;
    }

    @Override
    public EasyUITable search(String name,Integer currentPage) {
        IPage page = new Page(currentPage,6);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(Category::getName,name);
        categoryMapper.selectPage(page,queryWrapper);
        List<Category> list = page.getRecords();
        Integer total = (int)page.getTotal();
        return new EasyUITable(total,list);
    }

    public String getEmployeeId(){
        String token = request.getHeader("token");
        String EmployeeId = JwtUtil.validateToken(token);
        return EmployeeId;
    }
}
